package com.kfm.servlet;

import com.kfm.entity.User;
import com.kfm.util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/login2")
public class LoginServlet2 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        DBHelper dbHelper = new DBHelper();

        String sql = "select * from user where username = ? and password = ?";

        try {
            User user = dbHelper.selectOne(sql, User.class, username, password);
            if (user != null){
                // 登录成功
                String name = user.getName();

                writer.println("<h1>登录成功</h1>");
                writer.println("<h1>欢迎您，" + name + "</h1>");
                return;
            }
        } catch (SQLException e) {
            System.err.println("数据库查询异常");
        }

        response.sendRedirect("index.html");
    }
}
